const db = require("../db/mysql");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken")
const {jwtSecret,expiresIn}  = require("../config")
exports.loginUser  = (req,res)=>{
    const userinfo = req.body;
    const searchByUsername = "select * from ev_user where userName=?";
    let {username,password} = userinfo;
    db.query(searchByUsername,username,function(err,result){
        if (err) {
            // 执行sql语句失败
            return res.cc(err)
        }
        console.log(result);
        // sql语句成功，但获取到的数据不等于1
        if (result.length !== 1) {
            return res.cc("登录失败")
        }
        // 判断密码是否正确
        let compareResult= bcrypt.compareSync(password,result[0].userPwd);
        console.log(result[0].id);
        if(!compareResult){
            return res.cc("登录密码错误")
        }
        // 在服务器端生成 token字符串
        const user ={
            ...result[0],
            userPwd:"",
            userPic:""
        } 
        // 对用户的信息进行加密，生成token
        const tokenStr = jwt.sign(user,jwtSecret,{
            expiresIn
        });
        // 将token响应给客户端
        res.send({
            status:0,
            message:"登录成功！",
            token:"Bearer "+tokenStr,
            tokenTime:expiresIn,
            uid:result[0].id,
            isAdmin:result[0].isAdmin
        })
    })
}
exports.regUser  = (req,res)=>{
    const userinfo = req.body;
    const userIsExitSql = "select * from ev_user where userName=?";
    const insertUserSql = "insert into ev_user set ?";
    let {username,password} = userinfo;
    db.query(userIsExitSql,username,function(errs,resultes){
        if (errs) {
            return res.cc(err)
        }
        if (resultes.length>0) {
            return res.cc("用户名被占用，请更改其他用户名")
        }else{
            password = bcrypt.hashSync(password,10);
            console.log(username,password);
            db.query(insertUserSql,{
                userName:username,
                userPwd:password
            },function(err,resulte){
                if (err) {
                    return res.cc(err)
                }
                if (resulte.affectedRows !== 1) {
                    return res.cc("注册用户失败，请稍后再试")

                }
                return res.cc("注册成功",0)
            })
        }
    })
}
exports.getFile = (req,res)=>{
    res.sendFile("C:\\Users\\20164\\Desktop\\QQ截图20230115001056.png")
}